import { reqCartList, reqDeleteCartById, reqUpdateCheckedById } from '@/api';

//shopcar模块的仓库
const state = {
    cartList: []
};
const actions = {
    //获取购物车列表数据
    async getCartList({ commit }) {
        let result = await reqCartList();
        if (result.code == 200) {
            commit("GETCARTLIST", result.data);
        }
    },
    //删除购物车某个产品
    async deleteCartListBySkuId({ commit }, skuId) {
        let result = await reqDeleteCartById(skuId);
        if (result.code == 200) {
            return 'ok';
        } else {
            return Promise.reject(new Error('faile'));
        }
    },
    //修改购物车某一个产品的选中状态
    async updateCheckedById({ commit }, { skuId, isChecked }) {
        let result = await reqUpdateCheckedById(skuId, isChecked);
        if (result.code == 200) {
            return 'ok';
        } else {
            return Promise.reject(new Error('faile'));
        }
    },
    //删除全部勾选的产品
    async deleteAllCheckedCart({ dispatch, getters }) {
        //存储Promise的数组
        let PromiseAll = [];
        //获取购物车中全部的产品(是一个数组)
        getters.cartList.cartInfoList.forEach(item => {
            let promise = item.isChecked == 1 ? dispatch('deleteCartListBySkuId', item.skuId) : 'sss';
            PromiseAll.push(promise)
        });
        //只要全部的p1|p2...都成功，返回的结果即为成功；如果有一个失败，返回的即为失败
        return Promise.all(PromiseAll);
    },
    //修改全部产品的状态
    updateAllcartIschecked({state,dispatch},isChecked){
        //数组
        let promiseAll = [];
        state.cartList[0].cartInfoList.forEach((item) => {
            let promise = dispatch("updateCheckedById",{
                skuId: item.skuId,
                isChecked,
            });
            promiseAll.push(promise);
        });
        //最终返回结果
        return Promise.all(promiseAll);
    },
};
const mutations = {
    GETCARTLIST(state, cartList) {
        state.cartList = cartList;
    }
};
const getters = {
    cartList(state) {
        return state.cartList[0] || {};
    }
};
export default {
    state,
    actions,
    mutations,
    getters,
}